package repository

import (
	"context"
	"intelli-dl-online-logo-go/model"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type UserVipLogRepository interface {
	FindLastByUserID(ctx context.Context, userID primitive.ObjectID) (*model.UserVipLog, error)
}

type userVipLogRepository struct {
	collection *mongo.Collection
}

func NewUserVipLogRepository(db *mongo.Database) UserVipLogRepository {
	return &userVipLogRepository{
		collection: db.Collection("user_vip_logs"),
	}
}

func NewUserVipLogRepositoryImpl(db *mongo.Database) UserVipLogRepository {
	return &userVipLogRepository{
		collection: db.Collection("user_vip_logs"),
	}
}

func (r *userVipLogRepository) FindLastByUserID(ctx context.Context, userID primitive.ObjectID) (*model.UserVipLog, error) {
	var log model.UserVipLog

	opts := &options.FindOneOptions{
		Sort: bson.D{{Key: "endTime", Value: -1}},
	}

	err := r.collection.FindOne(
		ctx,
		bson.M{"userId": userID},
		opts,
	).Decode(&log)

	if err == mongo.ErrNoDocuments {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}

	return &log, nil
}
